<template>
  <section>
    <!-- 工具条：高级查询 + 添加 -->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="queryParams">
        <el-form-item>
          <el-input v-model="queryParams.keyword" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="advancedQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!-- 列表展示 -->
    <el-table :data="pageParams.types" highlight-current-row v-loading="listLoading" @selection-change="selsChange" @row-dblclick="getDetail"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" label="序号" width="60">
      </el-table-column>
      <el-table-column prop="name" label="字典名称" width="120" sortable >
      </el-table-column>
      <el-table-column prop="sn" label="字典编号" width="120" sortable>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 工具条：批量删除 + 分页栏 -->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="queryParams.pageSize" :total="pageParams.totals"
                     :current-page="queryParams.currentPage" style="float:right;">
      </el-pagination>
    </el-col>
<!-- 显示字典细节   -->
    <el-dialog title="当前数据字典明细列表" :visible.sync="dialogTableVisible">
      <el-table :data="details">
        <el-table-column type="index" label="序号" width="100">
        </el-table-column>
        <el-table-column prop="name" label="字典明细名称" sortable>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 新增或修改的模态框 -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="字典编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
export default {
  data() {
    return {
      //分页参数：分页列表 + 分页栏所需数据
      pageParams: {
        types: [],    //分页列表中：data
        totals: 0           //总页数：分页栏中显示
      },

      //定义查询参数：分页查询 + 高级查询
      queryParams: {
        pageSize: 5,      //分页查询参数：每页显示的条数 or 分页栏中显示
        currentPage: 1,   //分页查询参数：当前页 or 分页栏中显示
        keyword: ''       //高级查询参数：关键字查询
      },

      dialogTableVisible: false,
      listLoading: false,
      sels: [],//列表选中列

      title: "保存", //添加和修改的模态框的标题
      saveFormVisible: false,//编辑界面是否显示
      saveLoading: false,
      saveFormRules: {
        name: [
          {required: true, message: '请输入', trigger: 'blur'}
        ],
        sn: [
          {required: true, message: '请输入', trigger: 'blur'}
        ]
      },
      //编辑界面数据
      saveForm: {
        id: null,
        name: null,
        sn: null,
      },
      // 所有的字典明细
      details: null
    }
  },
  methods: {
    handleCurrentChange(val) {
      // console.log(val);
      this.queryParams.currentPage = val;
      this.getTypes();
    },
    // 高级查询方法
    advancedQuery() {
      this.queryParams.currentPage = 1;
      this.getTypes();
    },
    //获取数据明细列表
    getDetail(row) {
      this.listLoading = true; //忙等框
      // 发送请求
      this.$http.get("/details/" + row.id)
          .then(res => {
            // 讲数据的总条数赋值给totals
            this.pageParams.totals = res.data.totals;
            this.details = res.data;
            // console.log(this.details);
            // 关闭忙等框
            this.listLoading = false;
            this.dialogTableVisible = true;
          }).catch(res => {
        this.$message.error("系统错误");
      });
    },
    //获取部门列表
    getTypes() {
      this.listLoading = true; //忙等框
      // 发送请求
      this.$http.post("/dictionarytype", this.queryParams,)
          .then(res => {
            // 讲数据的总条数赋值给totals
            this.pageParams.totals = res.data.totals;
            this.pageParams.types = res.data.data;
            // console.log(res.data.data);
            // 关闭忙等框
            this.listLoading = false;
          }).catch(res => {
        this.$message.error("系统错误");
      });
    },
    // 是否为最后一页的最后一条数据
    isLastPage() {
      // 根据总的数据条数total和一页显示的数据条数，得到总页数
      let lastPage = this.pageParams.totals % this.queryParams.pageSize;
      // 判断当前页是否是最后一页且为最后一条数据
      if (lastPage == 1) {
        if (this.queryParams.currentPage == 0) {
          this.queryParams.currentPage = 1;
        } else {
          this.queryParams.currentPage--;
        }
      }
    },
    // 删除
    handleDel: function (index, row) {
      // 先判断是否为当前页最后一条数据
      this.isLastPage();
      if (this.queryParams.currentPage == 0) {
        this.queryParams.currentPage = 1;
      }
      // console.log(this.queryParams.currentPage + "dangqianye");
      this.$confirm('删除数据字典类型会同时删除数据字典明细,您确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        // 将当行的id拼接到url上
        let para = "/dictionarytype/" + row.id;
        this.$http.delete(para).then((res) => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getTypes();
          } else {
            this.$message({
              message: '删除失败',
              type: 'error'
            })
          }
        }).catch(res => {
          this.$message.error("系统错误,请稍后重试");
        });
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      // this.getType();
      this.saveFormVisible = true;
      this.title = "修改";
      this.saveForm = Object.assign({}, row);
    },
    //显示新增界面
    handleAdd: function () {
      // this.getType();
      this.title = "添加";
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        name: null,
        sn: null,

      };
    },
    // 所有类型
    getType() {
      // 发送请求
      this.$http.get("/dictionarytype").then(res => {
        this.departments = res.data;
      }).catch(res => {
        this.$message.error("系统错误,请稍后重试");
      })
    },
    //编辑
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);
            this.$http.put("/dictionarytype", para).then((res) => {
              this.saveLoading = false;
              if (res.data.success) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getTypes();
              } else {
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                })
              }
              this.$refs['saveForm'].resetFields();
              this.saveFormVisible = false;
              this.getTypes();
            });
          });
        }
      });
    },

    selsChange: function (sels) {
      this.sels = sels;
      // console.log(sels);
    },
    //批量删除
    batchRemove: function () {
      let ids = this.sels.map(item => item.id);
      this.$confirm('删除数据字典类型会同时删除数据字典明细,您确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        // let ids = { ids: id};
        // axios获取数据的格式都是res.data,然后再获取
        this.$http.patch("/dictionarytype", ids, {
          headers: {
            'Content-Type': 'application/json'
          }
        }).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.advancedQuery();
          }
        }).catch(res => {
          this.$message({
            message: '删除失败',
            type: 'error'
          });
        })
      }).catch(() => {

      });
    }
  },
  mounted() {
    //页面一加载 - 获取分页数据
    this.getTypes();
  }
}

</script>

<style scoped>

</style>